<?php
declare(strict_types=1);

namespace App\Controller\v1;

use App\Annotation\AuthUser;
use App\Controller\AbstractController;
use App\Request\Web\PublishArticleRequest;
use App\Request\Web\StoreArticleRequest;
use App\Service\Web\ArticleService;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PatchMapping;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller('/api/web/v1/articles')]
class ArticleController extends AbstractController
{
    #[Inject]
    private ArticleService $articleService;

    #[GetMapping('')]
    public function index()
    {
        $params = $this->request->getQueryParams();
        $page = (int) $this->request->query('page', 1);
        $perPage = (int) $this->request->query('perPage', 15);
        unset($params['page'], $params['perPage']);
        $authUserId = Context::has('uid') ? (int) Context::get('uid') : null;

        return $this->articleService->getPage($params, $authUserId, $page, $perPage);
    }

    #[GetMapping('{id}')]
    public function show(int $id, #[AuthUser] ?int $userId)
    {
        $ip = $this->request->getHeaderLine('X-Forwarded-For') ?: $this->request->getHeaderLine('Remote-Addr');

        return $this->articleService->show($id, $userId, $ip);
    }

    #[PostMapping('')]
    public function store(StoreArticleRequest $request, #[AuthUser] ?int $userId)
    {
        $data = $request->validated();

        return $this->articleService->store($data, $userId);
    }

    #[PatchMapping('{id}/review')]
    public function commitToReview(int $id, #[AuthUser] ?int $userId)
    {
        return $this->articleService->commitToReview($id, $userId);
    }

    #[PatchMapping('{id}/publish')]
    public function publish(int $id, PublishArticleRequest $request)
    {
        $data = $request->validated();

        $this->articleService->publish($id, $data);

        return [];
    }

    #[PostMapping('{id}/like')]
    public function like(int $id)
    {
        return $this->articleService->toggle($id);
    }
}